package com.iminutes.factory;

import com.iminutes.dao.UserDao;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

/**
 * @Description TODO
 * @Author liyuhua
 * @Date 2021/8/4 11:04
 **/
public class BeanFactory {
    //利用反射+xml返回实例化对象

    /**
     *
     * @param name
     * @return
     */
    public static Object createObjecct(String name){
        try {
            //实例化
            SAXReader sax = new SAXReader();
            //读取配置文件
            Document document = sax.read(BeanFactory.class.getClassLoader().getResourceAsStream("bean.xml"));
            //获取根节点
            Element element = document.getRootElement();
            //获取根节点下的子节点
            List<Element> elements = element.elements();
            //遍历节点
            for (Element el : elements) {
                //获取节点的ID
                String id = el.attributeValue("id");
                //判断和传递的name是否一致
                if(id.equals(name)){
                    //获取class类路径
                    String str = el.attributeValue("class");
                    Class<?> clazz = Class.forName(str);
                    return clazz.newInstance();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //测试
    public static void main(String[] args) {
        UserDao ud = (UserDao) BeanFactory.createObjecct("UserDao");
        ud.save();
    }


}
